<?php
/**
 *
 * @author ninteySeven.
 * @date 2022-12-13 0:16
 */

namespace App\Lib;

use App\Enum\CodeEnum;
use App\Enum\ThirdEnum;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JwtLib;
use Firebase\JWT\Key;

/**
 * jwt token
 * @author ninteySeven.
 * @date 2022-12-13 0:23
 */
class Jwt
{
    //加密
    public static function createToken($userId): string
    {
        $payload = array(
            "iss" => config('jwt.iss'),
            "aud" => config('jwt.aud'),
            "iat" => time(),
            "nbf" => time(),
            "exp" => config('jwt.exp') * 3,
            'user_id' => $userId
        );

        return JwtLib::encode($payload, config('jwt.key'), 'HS256');
    }

    // 生成 token 通用函数
    public static function createJwtToken($str): string
    {
        $payload = array(
            "iss" => config('jwt.iss'),
            "aud" => config('jwt.aud'),
            "iat" => time(),
            "nbf" => time(),
            "exp" => config('jwt.exp') * 3,
            'token' => $str
        );

        return JwtLib::encode($payload, config('jwt.key'), 'HS256');
    }

    //解密
    public static function decodeToken($token)
    {
        //token解析
        $decoded = JwtLib::decode($token, new Key(config('jwt.key'), 'HS256'));
        //解析返回值,json加密
        $decoded = json_encode($decoded);
        //解析返回值,json解密
        $decoded = json_decode($decoded, true);

        return $decoded;
    }
    public static function encodeThirdToken($code,$secretKey): string
    {
        $payload = array(
            "platform-code" => $code,
            "expire" => time()+env('THIRD_PLATFORM_TOKEN_EXPIRE',ThirdEnum::R_PLATFORM_JWT_EXPIRE_IN), // 过期时间
        );

        return JwtLib::encode($payload, $secretKey, 'HS256');
    }
    public static function decodeThirdToken($token,$secretKey)
    {
        //token解析
        $decoded = JwtLib::decode($token, new Key($secretKey, 'HS256'));
        //解析返回值,json加密
        $decoded = json_encode($decoded);
        //解析返回值,json解密
        return json_decode($decoded, true);
    }
}

